const { body } = require('express-validator')
const validate = require('../middleware/validator')
const { User } = require('../models/user')
const md5 = require('../utils/md5')


// 校验登录逻辑
exports.loginValidate = [
    validate([
        body('email')
            .notEmpty().withMessage('邮箱不能为空')
            .bail()
            .isEmail().withMessage('邮箱格式不正确'),
        body('password')
            .notEmpty().withMessage('密码不能为空')
    ]),
    validate([
        body('email')
            .custom(async (email, { req }) => {
                const user = await User.findOne({ where: { email } })
                if (!user) return Promise.reject('用户不存在')
                req.user = user
            })
    ]),
    validate([
        body('password')
            .custom(async (password, { req }) => {
                if (md5(password) !== req.user.password) {
                    return Promise.reject('密码不正确')
                }
            })
    ])
]

// 校验注册逻辑
exports.registerValidate = validate([
    body('username')
        .notEmpty().withMessage('用户名不能为空')
        .bail()
        .custom(async (username = '') => {
            const user = await User.findOne({ where: { username } })
            if (user) return Promise.reject('用户名已存在')
        }),

    body('password')
        .notEmpty().withMessage('密码不能为空'),

    body('email')
        .notEmpty().withMessage('邮箱不能为空')
        .bail()
        .isEmail().withMessage('邮箱格式不正确')
        .bail()
        .custom(async (email = '') => {
            const user = await User.findOne({ where: { email } })
            if (user) return Promise.reject('邮箱已存在')
        })
])
